﻿using System;
using System.Data;
using System.Data.Entity;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using Home.Domain.Entities;
using Omu.ValueInjecter;
using Utilities.Validation;
using Utilities.ViewModel;

namespace Home.WebUI.Areas.Mythi.Controllers
{
    [Home.WebUI.Areas.NewAdmin.Models.AdminLogin]
    public class NewsController : Controller
    {
        #region 基本
        private EFDbContext db = new EFDbContext();
        private DbSet<News> MEntity
        {
            get { return db.News; }
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        } 
        #endregion
        //
        // GET: /NewAdmin/News/

        public ActionResult Index(PagedList<News> model, int page = 1)
        {
            //页面项数
            const int pageSize = 10;
            var list = MEntity.Include(t => t.PNews).OrderByDescending(c => c.CreateDate).Skip((page - 1) * pageSize).Take(pageSize);
            if (!string.IsNullOrEmpty(model.Search))
            {
                list = list.Where(c => c.Title.Contains(model.Search));
            }
            model.Entities = list;
            model.PagingInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = pageSize, TotalItems = MEntity.Count() };
            return View(model);
        }

        public ActionResult Create()
        {
            NewsCreate model = new NewsCreate();
            model.CreateDate = DateTime.Now;
            DDLPNews();
            return View(model);
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(NewsCreate model)
        {
            //try
            //{
            if (model.UniValidate.CheckAll(Request))
            {
                News content = new News();
                content.InjectFrom(model);
                MEntity.Add(content);
                db.SaveChanges();
                TempData["Tip"] = new TipModel(1, "新建成功");
                return RedirectToAction("Index");
            }
            //}
            //catch (DataException)
            //{
            //    TempData["Tip"] = new TipModel(0, "无法保存更改。再试一次，和如果问题仍然存在，请联系您的系统管理员");
            //}
            DDLPNews(model.PNewsId);
            return View(model);
        }

        public ActionResult Edit(int id)
        {
            var model = new NewsCreate();
            model.InjectFrom(MEntity.Find(id));
            DDLPNews(model.PNewsId);
            return View(model);
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(NewsCreate model)
        {
            try
            {
                if (model.UniValidate.CheckAll(Request))
                {
                    var content = new News();
                    content.Id = model.Id;
                    MEntity.Attach(content);
                    content.InjectFrom(model);
                    db.SaveChanges();
                    TempData["Tip"] = new TipModel(1, "保存成功");
                    return RedirectToAction("Edit", new { id = model.Id });
                }
            }
            catch (DataException)
            {
                TempData["Tip"] = new TipModel(0, "无法保存更改。再试一次，和如果问题仍然存在，请联系您的系统管理员");
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            try
            {
                // TODO: Add delete logic here    
                if (Request.IsAjaxRequest())
                {
                    var content = MEntity.Find(id);
                    //int newsNumer = MEntity.Count(n => n.PNewsId == content.Id);
                    ////int newsNumer = content.News.Count();
                    //if (newsNumer > 0)
                    //{
                    //    return Content(newsNumer.ToString(CultureInfo.InvariantCulture));
                    //}
                    MEntity.Remove(content);
                    //EntityState stateafter = db.Entry(content).State;//Deleted状态     
                    int result = db.SaveChanges();
                    return Content("0");
                }
                else
                {
                    return Content("-1");
                }
            }
            catch
            {
                return Content("-1");
            }
        }

        private void DDLPNews(int? id=null)
        {
            ViewBag.PNewsId = new SelectList(db.PNews.OrderBy(t => t.Sort).ToList(), "Id", "Title",id);
        }

    }

    #region 验证类
    public class NewsCreate
    {
        public int Id { get; set; }
        public string Title { get; set; }
        /// <summary>
        /// 内容
        /// </summary>
        public string Body { get; set; }
        /// <summary>
        /// 标签
        /// </summary>
        public string Tags { get; set; }
        /// <summary>
        /// 描述
        /// </summary>
        public string Description { get; set; }
        /// <summary>
        /// 来源
        /// </summary>
        public string Source { get; set; }
        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreateDate { set; get; }
        /// <summary>
        /// 新闻类别Id,外键
        /// </summary>
        public int PNewsId { get; set; }
        public UniValidate UniValidate {
            get
            {
                var uv = new UniValidate();
                uv.InitName(() => Title).NotEmpty().MaxLength(36);
                uv.InitName(() => Body).NotEmpty();
                uv.InitName(() => Tags).MaxLength(20);
                uv.InitName(() => Description).MaxLength(200);
                uv.InitName(() => Source).MaxLength(200);
                uv.InitName(() => PNewsId).NotEmpty();
                uv.InitName(() => CreateDate).NotEmpty().DateTime();
                uv.ValidEnd(".form-horizontal");
                return uv;
            }
        }
    } 
    #endregion
}
